package com.yuyuy.ssm.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

/**
 * Spring核心配置类
 */
@Configuration
@ComponentScan("com.yuyuy.ssm.service")
@MapperScan("com.yuyuy.ssm.mapper")
@PropertySource("classpath:db.properties")
public class SpringConfig {
    /** 驱动类 */
    @Value("${db.driverName}")
    private String driver;
    /** 连接地址 */
    @Value("${db.url}")
    private String url;
    /** 用户名 */
    @Value("${db.username}")
    private String username;
    /** 密码 */
    @Value("${db.password}")
    private String password;

    /**
     * 构造数据库连接池放入容器
     * @return
     */
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    /**
     * 初始化mybatis核心对象   sqlSessionFactory
     * @param dataSource
     * @return
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }
}
